package com.jetpack_sunflower.workers

import android.content.Context
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.jetpack_sunflower.data.AppDataBase
import com.jetpack_sunflower.data.Plant
import com.jetpack_sunflower.utils.PLANT_DATA_FILENAME
import kotlinx.coroutines.channels.consumesAll
import java.lang.Exception

class SeedDatabaseWorker(val context: Context, workerParameters: WorkerParameters) : Worker(context, workerParameters) {

    private val tag by lazy { SeedDatabaseWorker::class.java.simpleName }

    override fun doWork(): Result {
        val plantType = object : TypeToken<List<Plant>>() {}.type
        var jsonReader: JsonReader? = null
        return try {
            val inputStream = applicationContext.assets.open(PLANT_DATA_FILENAME)
            jsonReader = JsonReader(inputStream.reader())
            val plantList = Gson().fromJson<List<Plant>>(jsonReader, plantType)
            val appDataBase = AppDataBase.getInstance(context = context)
            val plantDao = appDataBase.getPlantDao()
            plantDao.insertAllPlants(plantList)
            println("$tag 插入成功")
            Result.success()
        } catch (e: Exception) {
            println("$tag 插入失败")
            Result.failure()
        }
    }
}

/**
private val TAG by lazy { SeedDatabaseWorker::class.java.simpleName }

override fun doWork(): Result {
val plantType = object : TypeToken<List<Plant>>() {}.type
var jsonReader: JsonReader? = null

return try {
val inputStream = applicationContext.assets.open(PLANT_DATA_FILENAME)
jsonReader = JsonReader(inputStream.reader())
val plantList: List<Plant> = Gson().fromJson(jsonReader, plantType)
val database = AppDatabase.getInstance(applicationContext)
database.plantDao().insertAll(plantList)
Result.success()
} catch (ex: Exception) {
Log.e(TAG, "Error seeding database", ex)
Result.failure()
} finally {
jsonReader?.close()
}
}
 */